package bb.lanxing.adapter.sport;

import android.content.Context;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import bb.lanxing.R;
import bb.lanxing.util.DateUtil;

public class SportRecordCadenceAdapter extends RecyclerView.Adapter<SportRecordCadenceAdapter.ViewHolder> {
    private Context mContext;
    private int[] gradeStrings;
    private int[] gradeBgs;
    private int[] percents;
    private long duration;
    private int MaxPercent = 0;

    public class ViewHolder extends RecyclerView.ViewHolder {
        TextView grade;
        View rectangle;
        TextView time;
        TextView rate;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            grade = itemView.findViewById(R.id.grade);
            rectangle = itemView.findViewById(R.id.rectangle);
            time = itemView.findViewById(R.id.time);
            rate = itemView.findViewById(R.id.rate);
        }
    }

    public SportRecordCadenceAdapter(int[] gradeStrings, int[] gradeBgs, int[] percents, long duration) {
        this.gradeStrings = gradeStrings;
        this.gradeBgs = gradeBgs;
        this.percents = percents;
        this.duration = duration;
        for (int i = 0; i < percents.length; i++) {
            if (percents[i] > MaxPercent) {
                MaxPercent = percents[i];
            }
        }
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        mContext = parent.getContext();
        View view = LayoutInflater.from(mContext).inflate(R.layout.item_sport_record_cadence, parent, false);
        ViewHolder holder = new ViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.grade.setText(gradeStrings[position]);
        Drawable drawable = holder.rectangle.getBackground();
        drawable.setColorFilter(mContext.getColor(gradeBgs[position]), PorterDuff.Mode.SRC_ATOP);
        holder.rectangle.setBackground(drawable);
        ViewGroup.LayoutParams layoutParams = holder.rectangle.getLayoutParams();
        layoutParams.width = layoutParams.width * percents[position] / MaxPercent;
        holder.rectangle.setLayoutParams(layoutParams);

        holder.time.setText(DateUtil.format(percents[position] * duration * 10, 2));
        holder.rate.setText(percents[position] + "%");
    }

    @Override
    public int getItemCount() {
        return gradeStrings.length;
    }
}